#!/usr/bin/env bash

source localrc


function wait_volume_available() {
  for m in `seq 20`;do
    result=`openstack volume show $1|grep "\ status\ "|grep available`
    if [ x"$result" != x ];then
      return
    fi
    sleep 3
  done
  echo "error: volume $1 not available"
  exit 1
}


keypair=`openstack keypair list|grep "\ desktop\ "`
if [ x"$keypair" = x ];then
  openstack  keypair create --public-key ~/.ssh/id_rsa.pub desktop
fi

keypair="desktop"

for i in `seq $NUMBER`;do
  echo "ok: create bootable volume for ceph$i"
  volume_id=`openstack volume create --size 40 --image $IMAGE  --bootable ceph$i-root-disk|grep "\ id\ " $volume|awk '{print $4}'`
  echo "ok: wait bootable volume available for ceph$i"
  wait_volume_available $volume_id
  echo "ok: create server from bootable volume for ceph$i"
  openstack server create  --volume $volume_id --flavor $FLAVOR  --key-name $keypair --nic net-id=$NETWORK  ceph$i 1>/dev/null
done


for i in `seq $NUMBER`;do
  for n in `seq $VOLUME_PER_VM`;do
    echo "ok: create volume ceph$i-$n for ceph$i"
    volume_id=`openstack  volume create --size $VOLUME_SIZE ceph$i-$n|grep "\ id\ " $volume|awk '{print $4}'`
    echo "ok: wait volume ceph$i-$n available for ceph$i"
    wait_volume_available $volume_id
    echo "ok: attach volume ceph$i-$n for ceph$i"
    openstack server add volume ceph$i $volume_id
  done
done
